package actions.standard.form;

import gui.main.form.MainFrame;
import gui.main.form.NextDialog;
import gui.standard.form.StandardForm;

import java.awt.event.ActionEvent;
import java.sql.SQLException;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;

public class NextFormAction extends AbstractAction {

	private static final long serialVersionUID = 1L;
	private StandardForm standardForm;
	private boolean first = true;

	public NextFormAction(StandardForm standardForm) {
		putValue(SMALL_ICON, new ImageIcon("img/nextform.gif"));
		putValue(SHORT_DESCRIPTION, "Sledeca forma");
		this.standardForm = standardForm;

	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(standardForm.getChildren().size() > 1){
			if(first){
				for(StandardForm form : standardForm.getChildren())
					form.init();
			}
			
			NextDialog dialog = new NextDialog(MainFrame.getInstance(), standardForm.getChildren());
			dialog.setVisible(true);
			if(!dialog.isValueChosen())
				return;
			
			int index = dialog.getSelectedIndex();
			
			if(index == -1)
				return;
			
			try {
				standardForm.getChildren().get(index).getTableModel().searchRows(standardForm.getSelectedRowNextKeys(index));
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			standardForm.getChildren().get(index).setVisible(true);
			
		}else if(standardForm.getChildren().size() == 1){
			if(first){
				standardForm.getChildren().get(0).init();
				first = false;
			}
			try {
				standardForm.getChildren().get(0).getTableModel().searchRows(standardForm.getSelectedRowNextKeys(0));
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			standardForm.getChildren().get(0).setVisible(true);
		}
	}
}
